<template>
  <div v-loading="loading" class="theme-content-item" style="position: relative;">
    <div class="padding-20px">
      <div class="left-title">{{ title }}</div>
      <el-form ref="cooperationUnitRef" label-width="120px" :model="form" :rules="rules" :disabled="isView"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="排序" prop="orderNum">
              <el-input v-model="form.orderNum" type="number" placeholder="请输入排序号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-left: 20%">
            <el-form-item label="图标" prop="logoUrl" v-if="form.typeCode !== 'friendlyLink'">
              <el-upload class="avatar-uploader" name="fileList" :action="$uploadUrl" :headers="headers" :show-file-list="false"
                         :on-success="handleUploadSuccess" :on-error="handleUploadError" accept=".jpeg,.png,.jpg,.bmp">
                <img style="width: 150px; height: 150px; object-fit: scale-down;" v-if="form.logoUrl" :src="form.logoUrl"
                     class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">返回</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" :disabled="isDisabled" @click="confirmSave">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { getToken } from '@/utils/auth'
import {tableItem} from './const'
import {getCooperationUnitDetail, addCooperationUnit, editCooperationUnit} from '@/api/config/cooperation-unit'
const { proxy } = getCurrentInstance();
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const loading = ref(false)
const title = ref('');
const isAdd = ref(false);
const isView = ref(false);
const form = reactive({
  id: null,
  name: '',
  publishedFlag: 1,
  logoUrl: '',
  orderNum: null
},)

const rules = ({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  publishedFlag: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '请选择图标', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
})

function handleUploadSuccess(response) {
  form.logoUrl = response.data[0].url
  ElMessage({ message: "上传成功", type: 'success' })
}
function handleUploadError(Error) {
  ElMessage.error("上传失败")
}

// 详情
const initDetail = (row) => {
  getCooperationUnitDetail(row.id || route.query.id).then((res) => {
    Object.keys(form).forEach((key) => { form[`${key}`] = res.data[`${key}`] })
  })
}

const confirmSave = async () => {
  if (!isView.value) {
    proxy.$refs["cooperationUnitRef"].validate(valid => {
      if (valid) {
        loading.value = true
        if (isAdd.value) {
          addCooperationUnit(form).then(res => {
            if (res.code === 200) {
              loading.value = false
              goBack()
              tableItem.pageInfo.paging()
              ElMessage.success('新增成功');
            }
          })
        } else {
          editCooperationUnit(form).then(res => {
            if (res.code === 200) {
              loading.value = false
              goBack()
              tableItem.pageInfo.paging()
              ElMessage.success('修改成功');
            }
          })
        }
      }
    })
  } else {
    goBack()
  }
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}

onMounted(() => {
  let titleMap = {
    add: '新增合作单位',
    edit: '修改合作单位',
    view: '合作单位详情'
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type === 'view' ? isView.value = true : ''
  routeQuery.type === 'view' || route.query.type === 'edit' ? initDetail(route.query) : ''
  routeQuery.type === 'add' ? isAdd.value = true : ''
})
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.el-upload-list__item-info) {
  width: fit-content;

}

:deep(.el-input) {
  width: 400px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
